import {_decorator, Component, instantiate, Label, Node, Prefab, resources} from 'cc';
import {Pools} from '../../framework/entity/ao/Pools';
import {logUtil} from "../../framework/util/logUtil";
import {AttackType, PlayerCon} from './PlayerCon';
import {ActorActionManager} from "../../framework/manager/ActorActionManager";
import {AnimationEventListener} from '../../framework/listener/AnimationEventListener';
import {ProjectileEmitter} from '../projectile/ProjectileEmiter';
import {Constant} from "../../config/Constant";
import {LevelCon} from "./LevelCon";
import {Effect} from "../../framework/fight/IEffectContainer";
import {ActorProperty} from "../entity/ActorProperty";
import {EffectCon} from "./EffectCon";

const {ccclass} = _decorator;

@ccclass('AutoActorCon')
export class AutoActorCon extends Component {
    constructor(regime: string) {
        super();
        this.regime = regime;
        if(this.regime == Constant.DYNAMIC_RESOURCE.Actor.Forces1.Regime){
            this.enemyPath=Constant.DYNAMIC_RESOURCE.Actor.Forces1.Path
            this.projectilePath=Constant.DYNAMIC_RESOURCE.Projectile.Forces1.Path
        }else {
            this.enemyPath=Constant.DYNAMIC_RESOURCE.Actor.Forces2.Path
            this.projectilePath=Constant.DYNAMIC_RESOURCE.Projectile.Forces2.Path
        }
    }

    //日志控制器
    log = logUtil.instance
    logLevel = "AutoActorCon"

    //region 自己阵营对象池
    //阵营
    regime:string
    //预制体对象池
    enemyPools: Pools<string, Node> = new Pools();
    //名字
    private enemyNames: Array<string> = [];
    //场景中节点
    enemies: Array<Node> = [];
    enemyPath: string;
    //远程预制体
    projectilePath:string;
    projectilePrefab: Prefab | null = null;

    //endregion

    /**
     * 加载敌人模型
     */
    init(): Promise<any> {
        return new Promise((resolve) => {
            this.log.log(this.logLevel, `init`);
            //动态加载预制体
            resources.load(this.projectilePath,Prefab,
                (err, prefab) => {
                    if (err) {
                        this.log.log1(this.logLevel,Constant.LOG_CONTENT_LEVEL,this.log.LOG_LEVEL.ERROR,`点击了${this.regime}的远程预制体失败`, err)
                        return;
                    }
                    this.projectilePrefab = prefab

                    resources.loadDir(this.enemyPath,Prefab, (err,result) => {
                        for (let addressable of result) {
                            this.createEnemyPool(addressable);
                        }
                        resolve(result); // 所有资源加载完成后，解决Promise
                    });
                });

            this.log.log(this.logLevel, `加载结束`);
        });
    }

    /**
     * 敌人预制体处理
     */
    private createEnemyPool(prefab: Prefab) {
        //预制怪物对象配比
        const enemyCount = 1;
        this.enemyNames.push(prefab.name);
        this.enemyPools.newPool(
            prefab.name,
            (): Node => {
                let node = instantiate(prefab!);
                node.active = false;
                //构建脚本
                let playerCon = node.addComponent(PlayerCon);
                playerCon.actor = node.addComponent(ActorActionManager);
                //动画节点
                node.children[0].addComponent(AnimationEventListener)
                //名称节点
                node.children[1].getComponent(Label).string = node.uuid
                //初始化数据
                let data = LevelCon.instance.getBranchBataByName(prefab.name)
                playerCon.actor.data=data
                playerCon.actor.actorProperty.hp = data.hp
                playerCon.actor.actorProperty.maxHp = data.maxHp
                playerCon.actor.actorProperty.attack = data.attack
                playerCon.actor.actorProperty.agi = data.agi
                playerCon.actor.actorProperty.critRate = data.critRate
                playerCon.actor.linearSpeed = data.linearSpeed

                playerCon.attackRange = data.attackRange
                playerCon.fov = data.fov
                playerCon.vo = data.vo

                playerCon.regime = data.regime
                playerCon.career = data.career

                if (data.career == AttackType.Range && !node.getComponent(ProjectileEmitter)) {
                    let projectileEmitter = node.addComponent(ProjectileEmitter)
                    projectileEmitter.projectile = this.projectilePrefab
                    projectileEmitter.init()
                    playerCon.projectileEmitter = projectileEmitter
                }

                return node;
            },
            enemyCount,
            (node: Node) => {
                node.removeFromParent();
            }
        );
    }

    /**
     * 随机获取一个敌人节点
     * @param {Node} spawnNode 起点
     * @param {Node} destNode 终点
     * @param {ActorProperty} enhanceAttributes 增强属性
     */
    createRandomEnemy(spawnNode, destNode,enhanceAttributes?:ActorProperty) {
        // let name = this.enemyNames[math.randomRangeInt(0, this.enemyNames.length)];
        let name ='tnt'
        return this.FixedRole(name,spawnNode, destNode,enhanceAttributes)
    }

    clear() {
        this.enemyPools.destroyAll();
        this.enemyNames = [];
        this.enemies = [];
    }

    FixedRole(name: string, spawnNode, destNode,enhanceAttributes?:ActorProperty) {
        let node = this.enemyPools.allocc(name);

        let playerCon = node.getComponent(PlayerCon);
        playerCon.destForward = destNode.worldPosition;
        playerCon.actor.respawn()
        if(enhanceAttributes){
            playerCon.actor.actorProperty.hp+=enhanceAttributes.hp
            playerCon.actor.actorProperty.attack+=enhanceAttributes.attack
        }

        //zgnHelp buff1:初始触发buff-方法1
        if(this.regime == Constant.DYNAMIC_RESOURCE.Actor.Forces1.Regime){
            for (let i = 0; i <EffectCon.instance.skillList.length ; i++) {
                let buff=EffectCon.instance.skillList[i]
                if(buff.isBuff&&buff.triggerWay==Constant.EFFECT.TriggerWay.Init){
                    playerCon.actor.addBuff(EffectCon.instance.skillList[i])
                }
            }
        }else{
            for (let i = 0; i <EffectCon.instance.skillList.length ; i++) {
                let buff=EffectCon.instance.skillList[i]
                if(!buff.isBuff&&buff.triggerWay==Constant.EFFECT.TriggerWay.Init){
                    playerCon.actor.addBuff(EffectCon.instance.skillList[i])
                }
            }
        }
        //方法2
        /*EffectCon.instance.skillList.forEach(buff => {
            if (buff.triggerWay == Constant.EFFECT.TriggerWay.Init) {
                if(buff.isBuff&&this.regime == Constant.DYNAMIC_RESOURCE.Actor.Forces1.Regime){
                    playerCon.actor.addBuff(buff);
                }
                if(!buff.isBuff&&this.regime == Constant.DYNAMIC_RESOURCE.Actor.Forces2.Regime){
                    playerCon.actor.addBuff(buff)
                }
            }
        });*/

        node.active = true;

        spawnNode.addChild(node);
        this.enemies.push(node);
        this.log.log("fight", `生成{节点id:${node.uuid},角色:${name},位置:${node.position},血量:${playerCon.actor.actorProperty.hp},攻击力:${playerCon.actor.actorProperty.attack}}`)
        return node
    }
}


